
var Mqtt = require( 'mqtt' );
var mqtt = Mqtt.connect( "mqtt://127.0.0.1");

var stamp = 0;

var protectors = {};
const MAC_PREFIX = "123123456";
const IP_PREFIX = '10.1.11.';
function main() {

    for( let i = 0; i < 100; i++ ) {
        var mac =  MAC_PREFIX + i ;
        protectors[mac] = ( new Protector( mac,  IP_PREFIX + i ) );

        protectors[mac].start();
    }
    setTimeout( ()=> {
            console.log( "----------------" );
            produceAlarm( );
    }, 1000 * 10 );
}

mqtt.on( 'connect', ()=> {
    console.log( "----------------  connect mqtt broker success " );
    mqtt.subscribe( 'controller/#'  );
    mqtt.subscribe( 'query/#' );
    main();
});
mqtt.on( 'error' , ()=> {
    console.log( "error ----------" );
});


mqtt.on( 'message', ( topic, payload, packet ) => {

    var parts = topic.split( '/' );
    var main_topic = parts[0];
    if( main_topic == "controller" ) {
        handleController( parts, payload );
    }
    else if( main_topic == "query" ){
        handleQuery( parts, payload );
    }
});


function handleController( parts, payload ){

    var device_op = parts[1];
    var mac = parts[2];
    if( !protectors[mac] ){
        return ;
    }

    if( device_op == 'bufang' ){
        var aArmAreas = JSON.parse( payload.toString() );



        for( let idx in protectors[mac].arm_areas ) {
            protectors[mac].arm_areas[idx].s = 'b';
        }

        for( let i = 0; i < aArmAreas.length; i++ ) {
            protectors[mac].arm_areas[aArmAreas[i]].s = 'c' ;
        }

        let stamp = Date.now();
        protectors[mac].stamp = stamp;
        protectors[mac].status = 'b';


        setTimeout( ()=> {
            //after bufang ok,  send bufang ack
            mqtt.publish( 'monitor/status/' + mac, JSON.stringify( { type: 'armed', stamp:stamp } ) );
        }, 1000 * 4 );
    }
    else if( device_op == "chefang" ) {
        console.log( 'get chefang ');

        let stamp = Date.now();


        for( let i in protectors[mac].arm_areas ) {
            protectors[mac].arm_areas[i].s = 'c' ;
        }

        protectors[mac].status = 'c';
        protectors[mac].stamp = stamp;

        setTimeout( ()=> {
            //after bufang ok,  send bufang ack
            mqtt.publish( 'monitor/status/' + mac, JSON.stringify( { type: 'disarmed', stamp: stamp } ));
        }, 1000 * 4 );
    }
    else {
        console.log( "unexpected device operation " )
    }
}

function handleQuery( parts ) {
    console.log( " -------------------------------  get query message ---------------------- " );

    var mac = parts[1];

    if( mac == 'all' ){
        let all = {};
        for( let id in protectors ) {
            all[id] = {
                arm_areas: protectors[id].arm_areas,
                status: protectors[id].status,
                stamp: protectors[id].stamp
            }
        }
        mqtt.publish( "monitor/query/all", JSON.stringify( all ) ) ;
    }
    else if( protectors[mac] ) {
        var payload = JSON.stringify( protectors[mac].arm_areas );
        mqtt.publish( "monitor/query/" + mac,  payload );
    }
    else {
        console.log( 'unexpected query message, wrong mac ' );
    }
}


function Protector( mac, ip  ){
    this.mac = mac;
    this.arm_areas = {};

    for( let i = 1; i < 21 ; i++ ) {
        this.arm_areas[i] = { a: 0, s: 'c' };
    }

    this.toString = function() {
        return JSON.stringify({
            arm_areas:  this.arm_areas,
            status: this.status,
        });
    }
    this.start = function(){
        console.log( 'start '+ this.mac );
        protectors[this.mac].status = 'b';
        protectors[this.mac].stamp = Date.now();
        mqtt.publish( "start/" + ip + '/' + this.mac , JSON.stringify( "" ) );
    }
}



function produceAlarm(   ){
    var num = Date.now() %100;
    var mac = MAC_PREFIX + num;
    var arm_area_idx = num % 21;
   console.log( "\n------------" );
   setTimeout( ()=> {
       protectors[mac].status = 'a';
       mqtt.publish( "webServer/alarm/" + mac , JSON.stringify( { [arm_area_idx]: Date.now()  } ) );
       console.log( mac + ", " + arm_area_idx  + " alarm" );
       setTimeout( ()=> {
           mqtt.publish( 'monitor/status/' + mac , JSON.stringify( { type: 'alarmed', stamp: Date.now() }  ) );
           console.log( mac + " be alarmed" );
           produceAlarm();
       }, 3 * 1000 );
   }, 1000 * 2 )
}

